<template>
  <div class="create-post-page">
    <h4>新建文章</h4>
    <Uploader action="/upload" :before-upload="uploadCheck" @file-uploaded="handleFileUploaded" class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4">
      <h2>请点击上传图片，支持JPG或者PNG格式</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" role="status">
            <span class="visually-hidden">Loading...</span>
          </div>
          <h2> 正在上传...</h2>
        </div>
      </template>
      <template #uploaded="dataProps">
        <img :src="dataProps.uploadData.data.url" :alt="dataProps.uploadData.data.filename">
      </template>
    </Uploader>
    <ValidateFrom @from-submit="onSubmitForm">
      <div class="mb-3">
        <label class="form-label">文章标题：</label>
        <ValidateInput
          :rules="titleRules" v-model="titleVal"
          placeholder="请输入文章标题"
          type="text"
        />
      </div>
      <div class="mb-3">
        <label class="form-label">文章详情：</label>
        <ValidateInput
          rows="10"
          type="text"
          tag="textarea"
          placeholder="请输入文章详情"
          :rules="contentRules"
          v-model="contentVal"
        />
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">创建</button>
      </template>
    </ValidateFrom>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { GlobalDataProps, PostProps, ResponseType, ImageProps } from '../store'
import createMessage from '../components/createMessage'
import ValidateFrom from '../components/ValidateFrom.vue'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import Uploader from '../components/Uploader.vue'
import { beforeUploadCheck } from '../helper'

const titleVal = ref('')
const router = useRouter()
const store = useStore<GlobalDataProps>()
let imageId: string | undefined = undefined
const titleRules: RulesProp = [
  { type: 'required', message: '文章标题不能为空' }
]
const contentVal = ref('')
const contentRules: RulesProp = [
  { type: 'required', message: '文章详情不能为空' }
]
const handleFileUploaded = (rawData: ResponseType<ImageProps>) => {
  if (rawData.data._id) imageId = rawData.data._id
}
const onSubmitForm = (result: boolean) => {
  if (result) {
    const { column, _id } = store.state.user
    if (column) {
        const newPost: PostProps = {
        title: titleVal.value,
        content: contentVal.value,
        column,
        author: _id
      }
      if (imageId) {
        newPost.image = imageId
      }
      store.dispatch('createPost', newPost).then(() => {
        createMessage('文章创建成功', 'success')
        router.push(`/column/${column}`)
      })
    }
  }
}

const uploadCheck = (file: File) => {
    const result = beforeUploadCheck(file, { format: ['image/jpeg', 'image/png'], size: 1024 * 1024 })
    const { passed, error } = result
    if (error === 'format') {
        createMessage('图片格式不正确，仅支持jpg或者png格式', 'danger')
    }
    if (error === 'size') {
        createMessage('图片大小不能超过1M', 'danger')
    }
    return passed
}

</script>

<style>
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
}
.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>